package uade.distribuidas.server.dao;


import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import uade.distribuidas.repo.exception.ExceptionCliente;
import uade.distribuidas.repo.type.EstadoType;
import uade.distribuidas.server.domain.Cliente;
import uade.distribuidas.server.hibernate.HibernateUtil;

public class ClientesDAO {

	private static ClientesDAO instancia = null;
	private static SessionFactory sf = null;

	public static ClientesDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new ClientesDAO();
		} 
		return instancia;
	}
	
	@SuppressWarnings("unchecked")
	public List<Cliente> getClientes() throws ExceptionCliente{
		Session session = sf.openSession();
		
		List<Cliente> lista = session.createQuery("from Cliente where estado =:estado").setParameter("estado", EstadoType.ACTIVO).list();		
		
		session.close();
		return lista;
	}
	

	public Cliente getCliente(Integer id)throws ExceptionCliente{
		Session session = sf.openSession();
		
		Cliente c = (Cliente) session.createQuery("from Cliente where id = :id")
				.setParameter("id", id)
				.uniqueResult();		
		
		session.close();
		return c;
	}

	public Cliente save(Cliente c) throws ExceptionCliente{
		 Session session = sf.openSession();
		 Transaction transaction = session.beginTransaction();
		 transaction.begin();
		 session.saveOrUpdate(c);
		 transaction.commit();
		 session.close();
		 return c;
	}

	public Cliente getCliente(String cuil, String razonSocial) throws ExceptionCliente{
		Session session = sf.openSession();
		
		Cliente c = (Cliente) session.createQuery("from Cliente where cuil = :cuil and razonsocial = :razonsocial")
				.setParameter("cuil", cuil).setParameter("razonsocial", razonSocial)
				.uniqueResult();			
		
		session.close();
		return c;
	}

}
